<!--
/**
* @description 自定义规则
* @author wind-lc
* @date 2020-05-25
*/
-->
<template>
  <div class="page custom-rule-container">
    <form-loading :formLoadingVisible="!pageReady"></form-loading>
    <a-card title="规则名称"
            :bodyStyle="{padding:'10px'}">
      <a-form-model :model="form"
                    class="index-search-form-model"
                    ref="form"
                    :rules="rules"
                    layout="inline"
      >
        <a-form-model-item label="规则名称"
                           prop="name"
        >
          <a-input v-model="form.name"
                   :maxLength="50"
                   placeholder="请输入规则名称">
          </a-input>
        </a-form-model-item>
      </a-form-model>
    </a-card>
    <a-card title="规则条件"
            :bodyStyle="{padding:'10px'}"
            class="custom-rule-card">
      <!-- 规则条件 -->
      <a-form-model :model="searchForm"
                    class="index-search-form-model"
                    ref="searchForm"
                    :rules="searchRules"
                    layout="inline"
      >
        <a-form-model-item label="行政区域"
                           prop="area">
          <a-cascader v-model="searchForm.area"
                      :options="areaList"
                      :changeOnSelect="true"
                      :fieldNames="{ label: 'title', value: 'key', children: 'children' }"
                      placeholder="请选择区域" />
        </a-form-model-item>
        <a-form-model-item label="所属行业"
                           prop="industry">
          <a-select v-model="searchForm.industry"
                    placeholder="请选择行业">
            <a-select-option v-for="(item,index) in industryList"
                             :key="index"
                             :value="item.value">{{item.name}}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item class="top-widget-btn">
          <a-button type="primary"
                    shape="round"
                    icon="search"
                    @click="searchData">查询</a-button>
          <a-button @click="resetSearch"
                    shape="round"
                    icon="retweet"
          >重置</a-button>
        </a-form-model-item>
      </a-form-model>
      <!-- 规则条件 -->
    </a-card>
    <!-- 执行动作 -->
    <a-card title="执行动作"
            class="custom-rule-card">
      <ul class="custom-rule-action">
        <li class="custom-rule-source"
            ref="customRuleSource">
          <a-tree v-model="checkedKeys"
                  :showLine="true"
                  :showIcon="true"
                  :tree-data="treeData"
                  class="custom-rule-source-tree"
                  @select="treeSelect">
            <template slot="custom-folder" slot-scope="{ expanded }">
              <a-icon :type="expanded ? 'folder-open' : 'folder'" theme="filled"/>
            </template>
          </a-tree>
        </li>
        <li class="custom-rule-table"
            ref="customRuleTable">
          <a-table rowKey="equipmentIds"
                   :columns="columns"
                   :dataSource="data"
                   bordered
                   :rowSelection="{selectedRowKeys: selectedRowKeys,onChange: selectedRowChange}"
                   :loading="tableLoading"
                   @change="tableChange"
                   :pagination="pagination">
          </a-table>
        </li>
      </ul>
    </a-card>
    <!-- 执行动作 -->
    <div class="custom-rule-save">
      <a-button type="primary"
                @click="saveRule"
                :loading="confirmLoading"
                :disabled="saveDisabled">提交</a-button>
    </div>
  </div>
</template>
<script>
import { Card, FormModel, Input, Cascader, Select, Button, Tree, Table, Icon } from 'ant-design-vue'
import { getDictData, getTegionInfo } from '@/request/api/common'
import { getHnEntinfoAndWorkshop, queryAllRuleEquipment, queryChooseEquipmentIdUser, saveRule } from '@/request/api/ruleConfig/customRule'
import { getCustomIconTreeData } from '@/utils/index'
export default {
  name: 'customRule',
  components: {
    ACard: Card,
    AFormModel: FormModel,
    AFormModelItem: FormModel.Item,
    AInput: Input,
    ACascader: Cascader,
    ASelect: Select,
    ASelectOption: Select.Option,
    AButton: Button,
    ATree: Tree,
    ATable: Table,
    AIcon: Icon
  },
  data () {
    return {
      // 页面完成
      pageReady: false,
      // 数据字典
      dataDictionary: {},
      // 名称表单
      form: {},
      // 校验
      rules: {
        name: [
          {
            required: true,
            message: '请输入规则名称',
            trigger: 'change'
          }
        ]
      },
      // 顶部搜索表单
      searchForm: {},
      // 搜索校验
      searchRules: {
        area: [
          {
            required: true,
            message: '请选择区域',
            trigger: 'change'
          }
        ]
      },
      // 区域列表
      areaList: [],
      // 行业列表
      industryList: [],
      // 企业树
      treeData: [],
      // 选中的企业及生产线
      checkedKeys: [],
      // 自定义规则表头
      columns: [
        {
          title: '序号',
          align: 'center',
          ellipsis: true,
          width: 80,
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '设备名称',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentName'
        },
        {
          title: '设备ID',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentId'
        },
        {
          title: '污染分型',
          align: 'center',
          ellipsis: true,
          dataIndex: 'polluteType',
          customRender: (text, record, index) => {
            let txt = ''
            this.dataDictionary['Y-0B-008'].forEach(el => {
              if (text === el.value) {
                txt = el.name
              }
            })
            return txt
          }
        },
        {
          title: '设备状态',
          align: 'center',
          ellipsis: true,
          dataIndex: 'equipmentType',
          customRender: (text, record, index) => {
            let txt = ''
            this.dataDictionary['Y-002'].forEach(el => {
              if (text === el.value) {
                txt = el.name
              }
            })
            return txt
          }
        }
      ],
      // 表数据
      data: [],
      // 表格loading
      tableLoading: false,
      // 分页配置
      pagination: {
        current: 1, // 当前页数
        pageSize: 10, // 每页显示数量
        showQuickJumper: true, // 跳转
        showSizeChanger: true, // 显示改变每页数量
        total: 0, // 总数
        pageSizeOptions: ['10', '15', '20', '25'],
        showTotal: total => `共 ${total} 条` // 显示总数
      },
      // 规则选中
      selectedRowKeys: [],
      // 提交loading
      confirmLoading: false,
      // 企业选中信息
      equipmentInfo: {},
      // 提交禁用
      saveDisabled: true
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    // 初始化
    async init () {
      // 获取表格高度
      this.$refs.customRuleSource.style.height = this.$refs.customRuleTable.offsetHeight + 'px'
      // 获取区域列表
      this.getArea()
      // 获取数据字典
      this.dataDictionary = await this.getDataDictionary()
      // 写入行业列表
      this.industryList = this.dataDictionary['W-001'].map(el => {
        return {
          value: el.value,
          name: el.name
        }
      })
      this.pageReady = true
    },
    // 获取区域列表
    getArea () {
      getTegionInfo({}).then(res => {
        if (res.code === '0') {
          this.areaList = res.data
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 获取数据字典
    getDataDictionary () {
      return new Promise((resolve, reject) => {
        getDictData('W-001,Y-002,Y-0B-008').then(res => {
          resolve(res.data)
        }).catch(error => {
          reject(error)
          console.log(error)
        })
      })
    },
    // 查询企业树
    searchData () {
      this.$refs.searchForm.validate(valid => {
        if (valid) {
          this.pageReady = false
          getHnEntinfoAndWorkshop({
            areaCode: this.searchForm.area[this.searchForm.area.lenght - 1],
            industryCode: this.searchForm.industry,
            ruleType: '2'
          }).then(res => {
            if (res.code === '0') {
              this.treeData = getCustomIconTreeData(res.data)
            }
            this.pageReady = true
          }).catch(error => {
            console.log(error)
            this.pageReady = true
          })
        }
      })
    },
    // 重置
    resetSearch () {
      this.searchForm = {}
    },
    // 企业树选中
    treeSelect (selectedKeys, info) {
      if (selectedKeys.length > 0) {
        if (info.selectedNodes[0].data.props.dataRef.children) { // 点击企业
          this.getEquipmentData(selectedKeys[0])
        } else { // 点击生产线
          let entinfoId = ''
          for (let i = 0; i < this.treeData.length; i++) {
            if (this.treeData[i].children) {
              for (let j = 0; j < this.treeData[i].children.length; j++) {
                if (this.treeData[i].children[j].key === selectedKeys[0]) {
                  entinfoId = this.treeData[i].key
                  break
                }
              }
            }
          }
          this.getEquipmentData(entinfoId, selectedKeys[0])
        }
      }
    },
    // 获取设备数据
    getEquipmentData (entinfoId, workshopId = '') {
      // 记住选中信息
      this.equipmentInfo = {
        entinfoId: entinfoId,
        workshopId: workshopId
      }
      this.pageReady = false
      // 获取生产线或者企业设备
      queryAllRuleEquipment({
        pageNum: 1,
        pageSize: 10,
        param: {
          entinfoId: this.equipmentInfo.entinfoId,
          workshopId: this.equipmentInfo.workshopId
        }
      }).then(res => {
        if (res.code === '0') {
          this.data = res.data.list
        }
        // 获取选中设备列表
        queryChooseEquipmentIdUser({
          entinfoId: entinfoId,
          workshopId: workshopId,
          type: '2'
        }).then(res => {
          if (res.code === '0') {
            this.selectedRowKeys = res.data.map(element => element.equipmentIds)
          }
          this.pageReady = true
        }).catch(error => {
          console.log(error)
          this.pageReady = true
        })
        if (this.data.length > 0) {
          this.saveDisabled = false
        }
      }).catch(error => {
        console.log(error)
        this.pageReady = true
      })
    },
    // 选中行
    selectedRowChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 保存规则
    saveRule () {
      this.$refs.form.validate(valid => {
        if (valid) {
          saveRule({
            entinfoId: this.equipmentInfo.entinfoId,
            workshopId: this.equipmentInfo.workshopId,
            type: '2',
            hnRuleEquipmentList: [
              {
                equipmentIds: this.selectedRowKeys
              }
            ],
            name: this.form.name
          }).then(res => {
            this.confirmLoading = false
            this.tableLoading = false
            if (res.code === '0') {
              this.$message.success('提交成功!')
            }
          }).catch(error => {
            console.log(error)
            this.confirmLoading = false
            this.confirmLoading = false
            this.ruleData.forEach(el => {
              el.loading = false
            })
          })
        }
      })
    },
    // 表格变动
    tableChange (pagination, filters, sorter) {
      this.pagination = pagination
      this.$refs.customRuleSource.style.height = this.$refs.customRuleTable.offsetHeight + 'px'
      // 查询接口
      // this.searchData()
    }
  }
}
</script>
<style lang="scss">
.custom-rule-container {
  .ant-card-head {
    font-weight: bold;
  }
}
.custom-rule-card {
  margin-top: 20px;
}
.custom-rule-action {
  display: flex;
}
.custom-rule-source {
  width: 256px;
  margin-right: 20px;
  position: relative;
  &::before {
    content: '';
    display: block;
    width: 1px;
    height: calc(100% + 48px);
    position: absolute;
    top: -24px;
    right: 0;
    background-color: #e8e8e8;
  }
}
.custom-rule-table {
  flex: 1;
  min-height: 639px;
}
.custom-rule-save {
  padding-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.custom-rule-source-tree {
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  margin-right: 20px;
  span {
    max-width: 174px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
